/*
 * Copyright 2008 the original author Ang Gao.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * YahooSearcher.java 2008-12-1
 */
package ie.ucc.cs.anggao.finalproject.server.searchengine;

import ie.ucc.cs.anggao.finalproject.client.model.SearchEngineResult;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * @author GaoAng
 * 
 */
public class YahooSearcher extends BaseSearcher {

	// Yahoo API key
	private final String API_KEY = "v7zvQO3V34EOC7zHEP5t9Ii7cGUodHF_300VlYCINop0MEkJQlSIBcGXvgit0BtwX5uPtmKcIw--";

	private Queue<String> querys;

	private int resultnumber;

	public int getResultnumber() {
		return resultnumber;
	}

	public YahooSearcher() {
		super();
		querys = new LinkedList<String>();
	}
	
	
	public ArrayList<SearchEngineResult> getSEResults(){
		return this.results;
	}

	public void doIR(String q) {

		if (q.isEmpty())
			return;

		querys.add(q);
		q = querys.poll();
		results.clear();
		URLConnection connection;

		String line;
		StringBuilder builder = new StringBuilder();
		BufferedReader reader;

		JSONObject json;

		try {
			q = URLEncoder.encode(q, "UTF-8");

			// Give me back 10 results in JSON format
			URL url = new URL("http://boss.yahooapis.com/ysearch/web/v1/" + q
					+ "?appid=" + API_KEY + "&count=10&format=json");
			
			//Proxy
            InetSocketAddress addr = new InetSocketAddress("10.51.255.250",
                    8080);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); 
			
			
			connection = url.openConnection(proxy);

			// connection.addRequestProperty("Referer",
			// "http://www.mysite.com/index.html");

			reader = new BufferedReader(new InputStreamReader(connection
					.getInputStream()));

			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}

			json = new JSONObject(builder.toString());

			// System.out.println("Total results = "+
			// json.getJSONObject("ysearchresponse").getString("deephits"));

			JSONArray ja = json.getJSONObject("ysearchresponse").getJSONArray("resultset_web");

			this.resultnumber = ja.length();
			System.out.println("Yahoo Produce Results: " + ja.length());
			for (int i = 0; i < ja.length(); i++) {
				// System.out.print((i + 1) + ". ");
				JSONObject j = ja.getJSONObject(i);
				// System.out.println(j.getString("title"));
				// System.out.println(j.getString("url"));

				SearchEngineResult result = new SearchEngineResult();
				result.setTitle(j.getString("title"));
				result.setUrl(j.getString("url"));
				result.setDescription(j.getString("abstract"));

				results.add(result);

			}

//			return results;

		} catch (Exception e) {

			e.printStackTrace();
		}
//		return null;
	}
}
